package edu.rutgers.rucampusinfo.directory;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.rutgers.rucampusinfo.PMF;
import edu.rutgers.rucampusinfo.tables.Employee;
public class EmployeeDirectory extends HttpServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = -172420556006592977L;
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
		PrintWriter out = resp.getWriter();
		RequestDispatcher rd = null;
		resp.setContentType("text/html");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String sort = req.getParameter("sort");
		Query query = null;
		if (sort == null)
			sort = "last";
		
		out.write(sort);
		try{
			if ((sort.equals("last")) )
			{
			query = pm.newQuery("SELECT FROM "+Employee.class.getName()+" where inactive == \"FALSE\" order by lname");
			}
			else if (sort.equals("first"))
			{
			query = pm.newQuery("SELECT FROM "+Employee.class.getName()+" where inactive == \"FALSE\" order by fname");
			}
			List<Employee> results = (List<Employee>)query.execute();
			String size = String.valueOf(results.size());
			req.setAttribute("size", size);
			req.setAttribute("employeelist", results);
			req.setAttribute("sort", sort);
		    rd = getServletContext().getRequestDispatcher("/employeedir.jsp");
		    rd.forward(req, resp);
			for(Employee emp : results){
				out.write(emp.getFname());
			}
			
		}catch(Exception Ex)
		{
				Ex.printStackTrace(out);
		}
        finally {
        	pm.close();
        }
    }
}